/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * lista_usuarios.java
 *
 * Created on 11/10/2011, 20:10:22
 */
package usuario.visao;

import estruturas.Usuario;
import extras.LOG;
import extras.mensagens;
import extras.modelo.tblModelUsuario;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import usuario.banco.bd_user;
import usuarios.usuario;

/**
 *
 * @author Diego
 */
public class lista_usuarios extends javax.swing.JFrame
{

    bd_user users;
    Object valor, nome;
    LinkedList<String> usuarios = new LinkedList<>();
    LinkedList<Usuario> lista;
    LinkedList<String> aux = new LinkedList<>();
    tblModelUsuario model = new tblModelUsuario();

    /**
     * Creates new form lista_usuarios
     */
    public lista_usuarios()
    {
        try
        {
            lista = bd_user.getUsuarios();
            aux.add("Código");
            aux.add("Usuário");
            aux.add("Funcionário");
            users = new bd_user();

            refresh(1);
            model.setValores(new LinkedList<Object>(lista));
            model.setCabecalho(aux);
            initComponents();
            setLocationRelativeTo(null);
        } catch (SQLException ex)
        {
            Logger.getLogger(lista_usuarios.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void refresh(Integer i)
    {
        try
        {
            lista = bd_user.getUsuarios();
            model.setValores(new LinkedList<Object>(lista));
            usuarios.clear();

            for (Usuario t : lista)
            {
                usuarios.add(t.getNome().toLowerCase());
            }

            if (i == null)
            {
                tabela_usuarios.updateUI();
            }

        } catch (SQLException ex)
        {
            mensagens.mensagemErro("Erro ao capturar usuários!", "Ocorreu um erro ao adquirir os dados dos usuários!\n Tente novamente mais tarde.");
            LOG.add(ex.getMessage());
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela_usuarios = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Listar usuários");

        jLabel1.setText("Listando usuários");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/pencil.png"))); // NOI18N
        jButton1.setToolTipText("Editar");
        jButton1.setMaximumSize(new java.awt.Dimension(20, 20));
        jButton1.setMinimumSize(new java.awt.Dimension(20, 20));
        jButton1.setPreferredSize(new java.awt.Dimension(25, 25));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/user_delete.png"))); // NOI18N
        jButton2.setToolTipText("Apagar usuário");
        jButton2.setPreferredSize(new java.awt.Dimension(25, 25));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/cancel.png"))); // NOI18N
        jButton3.setText("Fechar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        tabela_usuarios.setAutoCreateRowSorter(true);
        tabela_usuarios.setModel(model);
        tabela_usuarios.setToolTipText("Usuários cadastrados no sistema");
        tabela_usuarios.setEditingRow(0);
        tabela_usuarios.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabela_usuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tabela_usuariosMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tabela_usuarios);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/user_add.png"))); // NOI18N
        jButton4.setToolTipText("adicionar usuário");
        jButton4.setPreferredSize(new java.awt.Dimension(25, 25));
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel1)
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21)
                .addComponent(jButton3)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
    {//GEN-HEADEREND:event_jButton2ActionPerformed
        int selRow = tabela_usuarios.getSelectedRow();

        if (selRow != -1)
        {
            try
            {
                valor = tabela_usuarios.getModel().getValueAt(selRow, 0);
                bd_user.delUsuario((int) valor);

                this.refresh(null);
                mensagens.mensagemOK("Usuario apagado com sucesso!");


            } catch (SQLException ex)
            {
                mensagens.mensagemErro("Erro ao apagar o usuário!", "Ocorreu um erro ao apagar o usuário!\n Tente novamente mais tarde.");
                LOG.add(ex.getMessage());
            }

        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton3ActionPerformed
    {//GEN-HEADEREND:event_jButton3ActionPerformed
        this.dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
        int selRow = tabela_usuarios.getSelectedRow();
        if (selRow != -1)
        {
            valor = tabela_usuarios.getModel().getValueAt(selRow, 0);
            nome = tabela_usuarios.getModel().getValueAt(selRow, 1);
            
            Usuario u = ((tblModelUsuario)tabela_usuarios.getModel()).getUsuario(selRow);
            user_add_edit t = new user_add_edit(u, this);
            
            t.setLocationRelativeTo(null);
            t.setVisible(true);

        } else
        {
            mensagens.mensagemErro("Erro!", "Você deve escolher um usuário para editar.");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton4ActionPerformed
    {//GEN-HEADEREND:event_jButton4ActionPerformed

        user_add_edit t = new user_add_edit(this);
        t.setLocationRelativeTo(null);
        t.setVisible(true);

    }//GEN-LAST:event_jButton4ActionPerformed

    private void tabela_usuariosMouseReleased(java.awt.event.MouseEvent evt)//GEN-FIRST:event_tabela_usuariosMouseReleased
    {//GEN-HEADEREND:event_tabela_usuariosMouseReleased
        if (evt.getClickCount() == 2)
        {
            jButton1ActionPerformed(null);
        }
    }//GEN-LAST:event_tabela_usuariosMouseReleased
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable tabela_usuarios;
    // End of variables declaration//GEN-END:variables
}
